#ifndef TRANSFERWORKER_H
#define TRANSFERWORKER_H

#include <QObject>
#include <QTcpSocket>
#include <QSslSocket>
#include <QFile>
#include "packagebuffer.h"
#include "SpinLock.h"

enum class WorkerMsg : quint16
{
    Invalid = 0,
    GetFileData,
    SendFileData,
    TransferFinish
};

class TransferWorker : public QObject
{
    Q_OBJECT
public:
    explicit TransferWorker(QObject *parent = nullptr);
    ~TransferWorker();

signals:
    void sendMsg(quint16 indx, quint16 msg);

public slots:
    void start();
    void stop();
    void receiveMsg(quint16 indx, quint16 msg, qint64 start, quint32 length);

private slots:
    void connected();
    void readyRead();
    void disconnected();
    void encrypted();
    void peerVerifyError(const QSslError &error);
    void modeChanged(QSslSocket::SslMode newMode);

public:
    void setIndex(uint16_t indx) { index = indx; }
    void setUploadFlag(uint64_t &flag) { uploadFlag = flag; }
    void setUseSsl(bool use) { useSsl = use; }
    void setServerIp(QString ip) {svrIp = ip; }
    void setServerPort(uint16_t port) {svrPort = port;}
    void setFile(QFile *file) {filePtr = file;}
    void setLock(CSpinLock *lock) { fileLock = lock; }

private:
    bool packageProcess();
    bool addUploader(uint8_t *buffer);
    bool fileBlockRequest(uint8_t *buffer, qint64 start, quint32 dataLen);
    bool fileBlockResponse(uint8_t *data, uint16_t size);
    bool transferFinish(uint8_t *buffer);

private:
    QTcpSocket *tcpSocket;
    PackageBuffer pkgBuffer;
    uint64_t uploadFlag;
    QFile *filePtr;
    QString svrIp;
    uint16_t svrPort;
    int16_t index;
    bool useSsl;
    int64_t blockOffset;
    uint32_t blockLength;
    uint32_t curLength;
    uint8_t *sendData;
    CSpinLock *fileLock;
};

#endif // TRANSFERWORKER_H
